<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

//-----------------------------------------------------------------------
// 系统环境是否满足要求?
//-----------------------------------------------------------------------
if (version_compare(phpversion(), '5.1.0', '<') == true) {
	die('Unsupported PHP version(PHP5.1+)');
}


//-----------------------------------------------------------------------
// 系统配置文件是否存在?
//-----------------------------------------------------------------------
if (!file_exists('config.php')) {
	header('Location: install.php');
	exit();
}

require_once 'config.php';


//-----------------------------------------------------------------------
// 初始化全局变量.
//-----------------------------------------------------------------------
if (!isset($_XOPTIONS)) {
	$_XOPTIONS = array();
}

if (!isset($_XAPPNAME)) {
	$_XAPPNAME = basename($_SERVER['SCRIPT_FILENAME'], '.php');
}

$micro_time = explode(' ', microtime());
$_XTIMESTAMP = intval($micro_time[1]);
$_XSTARTTIME = $_XTIMESTAMP + $micro_time[0];
unset($micro_time);

$_XCONFIG = $_XCOOKIE = $_XLANG = $_XJSTEXTS = $_XPARAMS
	= $_XEVENT = $_XMODULES = $_XPLUGINS = array();


//-----------------------------------------------------------------------
// 初始化基础模块.
//-----------------------------------------------------------------------
require_once DIR_SYSTEM . 'includes/import.php';
spl_autoload_register( 'otx_import_class');

otx_import_functions('commons', 'string', 'time', 'cache', 'event', 'module', 'plugin',
	'json', 'request', 'response', 'param', 'script', 'validate', 'html');

if (DEBUG) {
	error_reporting(E_ALL);
} else {
	error_reporting(E_ERROR | E_WARNING | E_NOTICE);
}

set_error_handler('otx_error_handler');
set_exception_handler('otx_exception_handler');

//trigger_error('XXXXXXXXXXX');
//trigger_error('XXXXXXXXXXX', E_DEPRECATED);

//-----------------------------------------------------------------------
// 初始化数据库服务.
//-----------------------------------------------------------------------
otx_import_functions('db');

$GLOBALS['_XDB'] = otx_db_connect(array(
	'dbtype' => DB_TYPE,
	'database' => DB_DATABASE,
	'host' => DB_HOST,
	'port' => DB_PORT,
	'username' => DB_USERNAME,
	'password' => DB_PASSWORD,
	'charset' => DB_CHARSET,
	'prefix' => DB_PREFIX
));


//-----------------------------------------------------------------------
// 初始化配置服务.
//-----------------------------------------------------------------------
otx_import_functions('config');

$_XCONFIG = otx_cache_fetch('config', true);
if (false === $_XCONFIG) {
	$_XCONFIG = array();

	$sql = 'SELECT * FROM #system_config#';
	$rows = otx_db_fetch_all($sql);

	if ($rows) {
		foreach ($rows as $row) {
			if ($row['serialized']) {
				$row['value'] = otx_string_unserialize($row['value']);
			}
			$_XCONFIG[$row['name']] = $row['value'];
		}
	}

	otx_cache_write('config', $_XCONFIG);
}

if (otx_config_bool('system_closed')) {
	die(otx_config_string('system_closed_reason'));
}

$time_zone = otx_config_int('system_time_zone');
date_default_timezone_set('Etc/GMT' . ($time_zone > 0 ? '-' : '+') . (abs($time_zone)));

unset($rows, $row, $time_zone);


//-----------------------------------------------------------------------
// 初始化Cookie服务.
//-----------------------------------------------------------------------
otx_import_functions('cookie');

$cookie_prefix = otx_config_string('system_cookie_prefix') . '_';
$prefix_length = strlen($cookie_prefix);

foreach ($_COOKIE as $cookie_key => $cookie_value) {
	if (substr($cookie_key, 0, $prefix_length) == $cookie_prefix) {
		$cookie_name = substr($cookie_key, $prefix_length);
		$GLOBALS['_XCOOKIE'][$cookie_name] = $cookie_value;
		unset($_COOKIE[$cookie_key]);
	}
}

unset($cookie_prefix, $prefix_length, $cookie_key, $cookie_value, $cookie_name);


//-----------------------------------------------------------------------
// 初始化会话服务.
//-----------------------------------------------------------------------
otx_import_functions('session');

$_SESSION = null;
$token = otx_session_token();

if (!empty($token)) {
	$sql = 'SELECT * FROM #system_session# WHERE token = ?';
	$row = otx_db_fetch_row($sql, $token);
	if ($row && $row['expiry'] >= $_XTIMESTAMP) {
		$_SESSION = otx_string_unserialize($row['value']);
	}
}

if (null === $_SESSION) {
	$_SESSION = array();
	otx_session_token(otx_string_uuid());
}

if (isset($_SESSION['user_id'])) {
	otx_session_login(intval($_SESSION['user_id']), null);
}

register_shutdown_function('otx_session_save');
unset($token, $row, $sql);


//-----------------------------------------------------------------------
// 获取使用者请求的路由参数. 如果没有指定, 则使用默认路由.
//-----------------------------------------------------------------------
$route = otx_param_string('route');

if (empty($route)) {
	if (isset($_XOPTIONS['default_route'])) {
		$route = $_XOPTIONS['default_route'];
	} else if (isset($_XOPTIONS['default_module'])) {
		$route = $_XOPTIONS['default_module'];
	} else if (isset($_XOPTIONS['main_module'])) {
		$route = $_XOPTIONS['main_module'];
	} else {
		$route = 'index';
	}
}

if (false !== strpos($route, '/')) {
	list($module_name, $controller_name) = explode('/', $route);
} else {
	$module_name = $route;

	if (isset($_XOPTIONS['default_controller'])) {
		$controller_name = $_XOPTIONS['default_controller'];
	} else {
		$controller_name = 'index';
	}
}

$action_name = otx_param_string('action');
if (empty($action_name)) {
	if (isset($_XOPTIONS['default_action'])) {
		$action_name = $_XOPTIONS['default_action'];
	} else {
		$action_name = 'index';
	}

	otx_param_set('action', $action_name);
}

otx_import_functions('router');
otx_router_module($module_name);
otx_router_controller($controller_name);
otx_router_action($action_name);
otx_param_set('route', $module_name . '/' . $controller_name);

unset($route, $module_name, $controller_name, $action_name);


//-----------------------------------------------------------------------
// 判断是否是AJAX请求?
//-----------------------------------------------------------------------
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
	&& $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
	$is_ajax = true;
} else if (otx_param_exists('is_ajax')) {
	$is_ajax = otx_param_bool('is_ajax');
} else {
	$is_ajax = false;
}

otx_param_set('is_ajax', $is_ajax);
unset($is_ajax);


//-----------------------------------------------------------------------
// 判断AJAX请求的内容范围(full, content, partial).
//-----------------------------------------------------------------------
if (otx_param_exists('ajax_scope')) {
	$ajax_scope = otx_param_string('ajax_scope');
} else {
	$ajax_scope = 'full';
}

otx_param_set('ajax_scope', $ajax_scope);
unset($ajax_scope);


//-----------------------------------------------------------------------
// 获取使用者指定的主题参数. 如果没有指定, 则使用默认主题.
//-----------------------------------------------------------------------
$theme_name = otx_param_string('theme');
if (empty($theme_name)) {
	$theme_name = 'admin';
}

otx_import_functions('theme');
otx_theme_name($theme_name);
unset($theme_name);


//-----------------------------------------------------------------------
// 获取使用者指定的语言参数. 如果没有指定, 则使用默认语言.
//-----------------------------------------------------------------------
$language_name = otx_param_string('language');
if (empty($language_name)) {
	$language_name = 'zh_CN';
}

otx_import_functions('language');
otx_language_name($language_name);
otx_language_load('module', 'system', 'system');
unset($language_name);


//-----------------------------------------------------------------------
// 初始化模块信息.
//-----------------------------------------------------------------------
$_XMODULES = otx_cache_fetch('modules');
if (false === $_XMODULES) {
	$_XMODULES = array();

	$sql = 'SELECT * FROM #system_module#';
	$rows = otx_db_fetch_all($sql);

	if ($rows) {
		foreach ($rows as $row) {
			$_XMODULES[$row['module_name']] = $row;
		}
	}

	otx_cache_write('modules', $_XMODULES);
}

foreach ($_XMODULES as $module) {
	if ($module['module_status']) {
		otx_event_register(otx_module_instance($module['module_name']), null);
	}
}

unset($sql, $rows, $row, $module);


//-----------------------------------------------------------------------
// 初始化插件信息.
//-----------------------------------------------------------------------
$_XPLUGINS = otx_cache_fetch('plugins');
if (false === $_XPLUGINS) {
	$_XPLUGINS = array();

	$sql = 'SELECT * FROM #system_plugin#';
	$rows = otx_db_fetch_all($sql);

	if ($rows) {
		foreach ($rows as $row) {
			$_XPLUGINS[$row['plugin_name']] = $row;
		}
	}

	otx_cache_write('plugins', $_XPLUGINS);
}

foreach ($_XPLUGINS as $plugin) {
	if ($plugin['plugin_status']) {
		otx_event_register(otx_plugin_instance($plugin['plugin_name']), null);
	}
}

unset($sql, $rows, $row, $plugin);


// //-----------------------------------------------------------------------
// // 执行路由控制器, 结果保存在$_XPARAMS[content]中.
// //-----------------------------------------------------------------------
// require_once otx_module_path('system', 'includes/functions_template.php');
// require_once otx_module_path('system', 'includes/functions_admin.php');
// otx_router_execute($route);


// //-----------------------------------------------------------------------
// // 执行主题输出, 返回响应内容.
// //-----------------------------------------------------------------------
// $response_content = otx_param_string('_content'); //otx_theme_render();


// //-----------------------------------------------------------------------
// // 输出响应内容. 如果启用了压缩还需要对响应内容再处理.
// //-----------------------------------------------------------------------
// if (otx_param_bool('is_ajax')) {
// 	otx_json_result($response_content);
// } else {
// 	if (!empty($GLOBALS['_XRESPONSE'])) {
// 		otx_html_response_output();
// 	} else {
// 		echo $response_content;
// 	}
// }
